import Util from "./Util";
import axios from "../../config/http";
let videoBaseUrl = "http://video.yueye7.com/";

let aliUtil = {
    "uploadState":1,
    "data":{
      title:"",
      fileName:"",
      oauthInfo:{
        uploadAddress: "",
        uploadAuth: "",
        videoId: ""
      },
      videoInfo:{
        fileName:"",
        flag:"2",
        thumFileName:"",
        description:"",
        length:0
      }
    },
    "uploader":{},
    init(data){
      let that = this;
      this.uploader = new AliyunUpload.Vod({
        // 文件上传失败
        'onUploadFailed': function (uploadInfo, code, message) {
          console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);
        },
        // 文件上传完成
        'onUploadSucceed': function (uploadInfo) {
          let VideoId = uploadInfo['videoId'];
          let VideoUrl = videoBaseUrl + uploadInfo['checkpoint']['name'];
          that.thumbPic(VideoUrl, function (res) {
            that.data.videoInfo.thumFileName = res[0]['url'];
            that.data.videoInfo.fileName = VideoId;
            that.data.videoInfo.length = uploadInfo['file']['size'];
            that.uploadState = 2;
          });
          document.getElementById("uploadInfoBox").innerHTML="获取数据中";
        },
        // 文件上传进度
        'onUploadProgress': function (uploadInfo, totalSize, loadedPercent) {
          let text = `正在上传的文件：${uploadInfo.file.name},大小：${totalSize},已上传${(loadedPercent * 100.00).toFixed(2)}%`;
          let p = document.createElement("p");
          p.innerHTML=text;
          let uploadDom = document.getElementById("uploadInfoBox");
          if(uploadDom){
            uploadDom.appendChild(p);
          }else{
            let uploadDom = document.createElement("div");
            uploadDom.setAttribute("id","uploadInfoBox");
            uploadDom.style.position = "fixed";
            uploadDom.style.top = 0;
            uploadDom.style.left = 0;
            uploadDom.style.width = "100%";
            uploadDom.style.color="red";
            uploadDom.style.fontSize = "16px";
            uploadDom.style.zIndex = 999;
            document.body.appendChild(uploadDom);
          }
        },
        // STS临时账号会过期，过期时触发函数
        'onUploadTokenExpired': function (uploadInfo) {
          console.log("onUploadTokenExpired");
            // uploader.resumeUploadWithAuth(uploadAuth);
        },
        onUploadCanceled:function(uploadInfo){
          console.log("onUploadCanceled:file:" + uploadInfo.file.name);
        },
        // 开始上传
        'onUploadstarted': function (uploadInfo) {
           console.log(uploadInfo);
           console.log(uploadInfo.videoId);
           console.log(!uploadInfo.videoId);
          if(!uploadInfo.videoId){
              let videoInfo = uploadInfo['videoInfo'];
              that.GetVideoAuth(uploadInfo, videoInfo['Title'], videoInfo['Description']);
            }else{
              that.RefreshUploadVideo(uploadInfo, uploadInfo.videoId);
            }
           
        },
        'onUploadEnd':function(uploadInfo){
          console.log("onUploadEnd: uploaded all the files")
        }
      });
    },
    GetVideoAuth(uploadInfo, title, desc){
      let that = this;
      let props = {
        url:"/Video/GetVideoAuth",
        data:{
          token:localStorage.getItem("token"),
          type:0,
          title:title,
          fileName:desc
        },
        sCallBack:(res) => {
          let oauthInfo = res['data']['data'];
          that.setOathAddress(uploadInfo, oauthInfo, "getOauth");
        },
        eCallBack:(err) => {
          console.log(err);
        }
      }
      Util.myRequest(props);
    },
    RefreshUploadVideo(uploadInfo, videoId){
      let that = this;
      let props = {
        url:"/Video/RefreshUploadVideo",
        data:{
            token:localStorage.getItem("token"),
            videoID:videoId
        },
        sCallBack:(res) => {
          let oauthInfo = res['data']['data'];
          that.setOathAddress(uploadInfo, oauthInfo, "refresh");
        },
        eCallBack:(err) => {
          console.log(err);
        }
      }
      Util.myRequest(props);
    },
    selectFile(e){
      this.fileName = "";
      this.flag = "2";
      this.thumFileName = "";
      this.description = "";
      this.length = 0;
      for(let i = 0; i < e.target.files.length; i++) {
          let userData = '{"Vod":{"StorageLocation":"","Title":"' + e.target.files[i].name + '","Description":"' + e.target.files[i].name + '"}}';
          this.uploader.addFile(e.target.files[i], null, null, null, userData);
      }
    },
    startUpload(){
      this.uploader.startUpload();
    },
    setOathAddress(uploadInfo, oauthInfo, type){
      if(type === "refresh"){
        this.uploader.setUploadAuthAndAddress(uploadInfo, oauthInfo['uploadAuth'], oauthInfo['uploadAddress']);
      }else{
        this.uploader.setUploadAuthAndAddress(uploadInfo, oauthInfo['uploadAuth'], oauthInfo['uploadAddress'], oauthInfo['videoId']);
      }
    },
    // 截取封面图
    thumbPic(videoUrl, callback){
        let that = this;
        let oVideoEle = document.createElement("VIDEO");
        oVideoEle.setAttribute("src", videoUrl);
        oVideoEle.setAttribute("crossOrigin", "anonymous");
        oVideoEle.oncanplay = function(){
          let canvas = document.createElement("canvas");
          canvas.width = oVideoEle.videoWidth;
          canvas.height = oVideoEle.videoHeight;
          canvas.getContext('2d').drawImage(oVideoEle, 0, 0, canvas.width, canvas.height);
          let dataUrl = canvas.toDataURL("image/jpeg");
          let base64 = dataUrl.split(',')[1].replace(/\s/g, '');
          // 如果封面图的数据大于1M压缩一半
          let fileSize = base64.length / 1024 / 1024;
          if (fileSize > 1) base64 = canvas.toDataURL('image/jpeg', 0.5);
          let fileType = dataUrl.split(';')[0].split(':')[1];
          let blob = that.toBlob(base64, fileType);
          that.uploadThumbImg(blob, callback);
        }
    },
    // 转blob对象
    toBlob(urlData, fileType){
      let bytes = window.atob(urlData);
      let n = bytes.length;
      let u8arr = new Uint8Array(n);
      while(n--){
        u8arr[n] = bytes.charCodeAt(n);
      }
      return new Blob([u8arr], {type:fileType});
    },
    // 上传封面图到服务器
    uploadThumbImg(blob, callback){
      let that = this;
        this.canvasDataURL(blob, function (value) {
            let base64 = value.split(',')[1].replace(/\s/g, '');
            let fileType = value.split(';')[0].split(':')[1];
            let newBlob = that.toBlob(base64, fileType);
            let Form = new FormData();
            Form.append("content", newBlob);
            Form.append("token", localStorage.getItem("token"));
            Form.append("type", 0);
            Form.append("clientType", "pc");
            let config = {
              headers: {
                'client':"pc",
                'Content-Type': 'multipart/form-data;charset=utf-8'
              }
            }
            axios.post('/Upload/UploadImg', Form, config).then(function (response) {
              if (response.status === 200) {
                callback(response['data']['data']);
              }
            })
        })
    },
   canvasDataURL(fileData, callback) {
      let reader = new FileReader();
      reader.onload = function (e) {
          let data = e.target.result;
          let image = new Image();
          image.src = data;
          image.setAttribute("crossOrigin", 'Anonymous');
          image.onload = function(){
             let w = image.width;
             let h = image.height;
             let scale = w / h;
            if (w > 1280 && h > 1280) {
              if (w > h) {
                h = 1280;
                w = h * scale;
              } else {
                w = 1280;
                h = w / scale;
              }
            } else if (w > 1280 || h > 1280) {
              if (scale >= 0.5 && scale <= 2) {
                if (w > h) {
                  w = 1280;
                  h = w / scale;
                } else {
                  h = 1280;
                  w = h * scale;
                }
              }
            }
            // 生成canvas
            let canvas = document.createElement('canvas');
            let ctx = canvas.getContext('2d');
            // 创建属性节点
            let anw = document.createAttribute("width");
            anw.nodeValue = w;
            let anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(image, 0, 0, w, h);
            // 生成base64的图片数据
            let base64 = canvas.toDataURL('image/jpeg', 1);
            let fileSize = base64.length / 1024 / 1024;
            if (fileSize > 1) base64 = canvas.toDataURL('image/jpeg', 0.5);
            callback(base64);
          };
      };
      reader.readAsDataURL(fileData);
   }
};

export default aliUtil;
